package edu.pod.hoteishilton.dao;

import edu.pod.hoteishilton.model.Hotel;
import edu.pod.hoteishilton.persistence.Configuration;
import edu.pod.hoteishilton.persistence.FileIOException;
import edu.pod.hoteishilton.persistence.FileObjectContainer;
import java.io.*;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public abstract class DAOFile extends UnicastRemoteObject implements DAOInterface {
    protected static FileObjectContainer manager;
    protected static int contador;

    public DAOFile() throws RemoteException {
        getManager();
    }

    protected static FileObjectContainer getManager() {
        if (manager == null) {
            manager = new FileObjectContainer(configuracao());
        }
        return manager;
    }

    protected static Configuration configuracao() {
        Configuration conf = FileObjectContainer.newConfiguration();
        conf.setDatabasePath(".\\database\\");
        conf.setDatabaseExtension("dat");
        conf.setDatabaseName("hoteishilton");
        return conf;
    }

    
    public void close() {
        if(manager != null){
            try {
                manager.close();
                manager = null;
            } catch (FileIOException ex) {
                Logger.getLogger(DAOFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void begin() {
        getManager();
    }

    public void commit() throws Exception{
        getManager().commit();
    }
    
    /*
    * METODO PARA GERAR ID's DE UMA DETERMINADA CLASSE 
    * ------ ---- ----- ---- -- --- ----------- ------
    * O hashmap contadores contem o ultimo ID gerado para 
    * cada classe e é indexado pelo nome da classe
    */
    public static synchronized int gerarId() throws FileNotFoundException, IOException {
        int numero = 0;
        if(!new File(".\\database\\contador.dat").exists()){
            BufferedWriter writer = new BufferedWriter(new FileWriter(".\\database\\contador.dat"));
            numero++;
            writer.write(String.valueOf(numero));  
            writer.close();
            System.out.println("Gerou arquivo de contador.");
        }else{
            BufferedReader reader = new BufferedReader(new FileReader(".\\database\\contador.dat"));  
            numero = Integer.parseInt(reader.readLine());
            numero++;
            reader.close(); 
        
            BufferedWriter writer = new BufferedWriter(new FileWriter(".\\database\\contador.dat"));
            writer.write(String.valueOf(numero));  
            writer.close();
        }
        return numero;
    }
}